<template>
  <l-layout class="l-tab-page" :right="500">
    <l-panel style="padding-right: 0">
      <template #title>
        <el-button-group style="margin-right: 8px">
          <el-tooltip effect="dark" :content="$t('撤销')" placement="bottom">
            <el-button
              size="mini"
              icon="el-icon-refresh-right"
              @click="handlerUndo"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" :content="$t('重做')" placement="bottom">
            <el-button
              size="mini"
              icon="el-icon-refresh-left"
              @click="handlerRedo"
            ></el-button>
          </el-tooltip>
        </el-button-group>
        <el-button-group>
          <el-tooltip effect="dark" :content="$t('复原')" placement="bottom">
            <el-button
              size="mini"
              icon="el-icon-aim"
              @click="resetZoom"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" :content="$t('放大')" placement="bottom">
            <el-button
              size="mini"
              icon="el-icon-zoom-in"
              @click="handlerZoom(0.1)"
            ></el-button>
          </el-tooltip>
          <el-tooltip effect="dark" :content="$t('缩小')" placement="bottom">
            <el-button
              size="mini"
              icon="el-icon-zoom-out"
              @click="handlerZoom(-0.1)"
            ></el-button>
          </el-tooltip>
        </el-button-group>
      </template>
      <b-wflow
        ref="bflow"
        @elementCreate="elementCreate"
        @elementClick="elementClick"
        @elementRemoved="elementRemoved"
      >
      </b-wflow>
    </l-panel>
    <template #right>
      <l-panel style="padding-left: 0">
        <div class="l-auto-window h48">
          <el-tabs v-model="configActiveName" @tab-click="tabClick" :stretch="true">
            <el-tab-pane
              :label="$t(wfNodeName[currentWfNode.type])"
              name="tab01"
              v-if="currentWfNode != undefined"
            >
              <component
                ref="wfcongfig"
                :is="`${currentWfNode.type}Option`"
              ></component>
            </el-tab-pane>
            <el-tab-pane :label="$t('流程属性')" name="tab02">
              <shcemeinfo-config ref="shcemeinfo"></shcemeinfo-config>
            </el-tab-pane>
            <el-tab-pane :label="$t('发起权限')" name="tab03">
              <auth-config
                ref="auth"
                :description="$t('所有人员指:不限制流程模版的发起人员，表示每个人都能发起该流程。')"
              ></auth-config>
            </el-tab-pane>
            <el-tab-pane :label="$t('监控权限')" name="tab04">
              <auth-config
                ref="authMonitor"
                :description="$t('所有人员指:不限制流程模版的监控人员，表示每个人都能监控该流程。')"
              ></auth-config>
            </el-tab-pane>
            <el-tab-pane :label="$t('批量打印权限')" name="tab05">
              <auth-print-config
                ref="authPrint"
                :wfData="wfData"
              ></auth-print-config>
            </el-tab-pane>
          </el-tabs>
        </div>
      </l-panel>
    </template>
  </l-layout>
</template>
<script>
import shcemeinfoConfig from "./config/shcemeInfo";
import authConfig from "./config/auth";
import authPrintConfig  from "./config/authPrint";

import startEventOption from "./config/startEvent";
import endEventOption from "./config/endEvent";
import gatewayAndOption from "./config/gatewayAnd";
import gatewayInclusiveOption from "./config/gatewayInclusive";
import gatewayXorOption from "./config/gatewayXor";
import scriptTaskOption from "./config/scriptTask";
import subprocessOption from "./config/subprocess";
import userTaskOption from "./config/userTask";
import mylineOption from "./config/myline";

export default {
  provide() {
    return {
      wfdesign: this,
    };
  },
  components: {
    shcemeinfoConfig,
    authConfig,
    authPrintConfig,

    startEventOption,
    endEventOption,
    gatewayAndOption,
    gatewayInclusiveOption,
    gatewayXorOption,
    scriptTaskOption,
    subprocessOption,
    userTaskOption,
    mylineOption,
  },
  data() {
    return {
      wfData: [],
      configActiveName: "tab02",
      currentWfNode: undefined,
      wfNodeName: {
        startEvent: "开始节点",
        endEvent: "结束节点",
        gatewayAnd: "并行网关",
        gatewayInclusive: "包含网关",
        gatewayXor: "排他网关",
        scriptTask: "脚本节点",
        userTask: "审核节点",
        subprocess: "子流程",
        myline: "线条",
      },

      custmerformSchemes: {},

      formData: {},
      rules: {},
      dbTableData: [],
      dbtableSelectdialog: false,
      schemeinfoId: "",
    };
  },
  computed: {},
  created() {},
  methods: {
    // 属性设置调整
    tabClick(){
      
      if(this.configActiveName == 'tab05'){
        this.wfData = this.handleGetWFData();



        console.log(this.wfData,'tabClick');
      }
     
      
    },

    // 流程图方法
    handlerUndo() {
      this.currentWfNode = undefined;
      this.configActiveName = "tab02";
      this.$refs.bflow.handlerUndo();
    },
    handlerRedo() {
      this.$refs.bflow.handlerRedo();
    },
    resetZoom() {
      this.$refs.bflow.reset();
    },
    handlerZoom(r) {
      this.$refs.bflow.handlerZoom(r);
    },
    handleGetWFData() {
      return this.$deepClone(this.$refs.bflow.getData());
    },

    // 流程元素点击
    elementCreate(node) {
      let nodeInitFn = this[`${node.type}NodeInit`];
      nodeInitFn && nodeInitFn(node);
      node.isInit = true;
      this.elementClick(node);
    },
    elementClick(node) {
      if (node && !node.type) {
        node = undefined;
      }

      this.currentWfNode = node;
      if (node == undefined) {
        this.configActiveName = "tab02";
      } else {
        if (!node.isInit) {
          let nodeInitFn = this[`${node.type}NodeInit`];
          nodeInitFn && nodeInitFn(node);
          node.isInit = true;
        }

        if (node.type == "myline") {
          this.$nextTick(() => {
            this.$refs.wfcongfig && this.$refs.wfcongfig.getConditions();
          });
        }

        this.configActiveName = "tab01";
      }
    },
    elementRemoved() {
      this.configActiveName = "tab02";
      this.currentWfNode = undefined;
    },

    // 流程节点初始化
    startEventNodeInit(node) {
      node.isNextAuditor = false;
      node.isCustmerTitle = false;
      node.isDelete = false;
      node.isRejectBackOld = true;
      node.formRelations = [];
      
      node.formWrodPrintCode = "";
      node.formType = "1";
      node.formCode = "";
      node.formVerison = "";
      node.formRelationId = "";
      node.formUrl = "";
      node.formAppUrl = "";
      node.authFields = [];
      node.messageType = "";

    },
    gatewayXorNodeInit(node) {
      node.conditions = [];
    },
    gatewayInclusiveNodeInit(node) {
      node.conditions = [];
    },
    userTaskNodeInit(node) {
      node.isAddSign = false;
      node.isTransfer = false;
      node.isBatchAudit = false;
      node.isUploadFile = false;

      node.autoAgree = "";
      if(this.appConfig.notShowAdmin){
        node.noAuditor = "4";
      }
      else{
        node.noAuditor = "1";
      }
      
      node.rejectType = "1";
      node.rejectNeedForm = false
      node.isRejectBackOld = true
      node.messageType = "";

      node.auditUsers = [];
      node.lookUsers = [];
      node.formRelations = [];

      node.formWrodPrintCode = "";
      node.formType = "1";
      node.formCode = "";
      node.formVerison = "";
      node.formRelationId = "";
      node.formUrl = "";
      node.formAppUrl = "";
      node.authFields = [];
      node.name = "审核节点";
      node.btnlist = [
        {
          code: "agree",
          name: "同意",
          hidden: false,
          isNextAuditor: false,
          isSign: false,
          isSys: true,
        },
        {
          code: "disagree",
          name: "驳回",
          hidden: false,
          isNextAuditor: false,
          isSign: false,
          isSys: true,
        },
      ];

      node.isCountersign = false;
      node.isCountersignAll = false;
      node.countersignAgian = "1";
      node.countersignType = "1";
      node.countersignAllType = 100;

      node.isOvertimeMessage = false;
      node.overtimeMessageType = "";
      node.overtimeMessageStart = 1; // 单位小时
      node.overtimeMessageInterval = 1;

      node.isOvertimeGo = false;
      node.overtimeGo = 12;

      // 是否继承开始组件表单
      node.isInherit = true;

      this.$refs.bflow.updateElemet(node);
    },
    scriptTaskNodeInit(node) {
      node.executeType = "1";
      node.sqlDb = "";
      node.sqlStr = "";
      node.sqlStrRevoke = "";
      node.apiUrl = "";
      node.apiUrlRevoke = "";
      node.ioc = "";
      node.iocRevoke = "";
    },
    subprocessNodeInit(node) {
      node.name = "子流程";
      node.isAuto = true;
      node.auditUsers = [];
      node.wfschemeId = "";
      node.wfVersionId = "";
      node.executeType = "1";
      node.sqlDb = "";
      node.sqlStr = "";
      node.sqlStrRevoke = "";
      node.apiUrl = "";
      node.apiUrlRevoke = "";
      node.ioc = "";
      node.iocRevoke = "";
      node.messageType = "";

      this.$refs.bflow.updateElemet(node);
    },
    mylineNodeInit(node) {
      const wfdata = this.handleGetWFData();
      const fromNode = wfdata.find((t) => t.id == node.from);
      node.lineConditions = "";
      if (fromNode.type == "userTask") {
        if (
          fromNode.btnlist.findIndex((t) => t.code == "agree" && !t.hidden) !=
          -1
        ) {
          node.lineConditions = "agree"; // 流转条件
        }
      } else if (fromNode.type == "subprocess") {
        node.lineConditions = "agree"; // 流转条件
      }
    },

    // 表单方法
    resetForm() {
      this.configActiveName = "tab02";
      this.currentWfNode = undefined;
      this.schemeinfoId = "";
      this.$refs.shcemeinfo && this.$refs.shcemeinfo.resetForm();
      this.$refs.auth && this.$refs.auth.resetForm();
      this.$refs.authMonitor && this.$refs.authMonitor.resetForm();
      this.$refs.authPrint && this.$refs.authPrint.resetForm();
      this.$refs.bflow.setData([]);
    },
    async validateForm() {
      const res = await this.$refs.shcemeinfo.validateForm();

      if (res) {
        let authPrintValidate = this.$refs.authPrint.validateForm();
        if(!authPrintValidate){
          return false;
        }

        const wfData = this.handleGetWFData();
        if (wfData.length == 0) {
          this.$message({
            type: "warning",
            message: this.$t("请设置【流程模版】!"),
          });
          return false;
        }

        if (wfData.find((t) => t.type == "startEvent") == null) {
          this.$message({
            type: "warning",
            message: this.$t("请设置【开始节点】!"),
          });
          return false;
        }

        if (wfData.find((t) => t.type == "endEvent") == null) {
          this.$message({
            type: "warning",
            message: this.$t("请设置【结束节点】!"),
          });
          return false;
        }

        for (let i = 0, len = wfData.length; i < len; i++) {
          const wfItem = wfData[i];
          if (wfItem.type == "startEvent" || wfItem.type == "userTask" || wfItem.type == "subprocess") {
            wfItem.strokeColor = "#000";
            this.$refs.bflow.updateElemet(wfItem);
          }
        }

        for (let i = 0, len = wfData.length; i < len; i++) {
          const wfItem = wfData[i];
          if (wfItem.type == "startEvent") {
            if (
              wfItem.formType == "1" &&
              wfItem.formCode &&
              !wfItem.formRelationId
            ) {
              this.$message({
                type: "warning",
                message: this.$t("请设置【开始节点】表单关联字段!"),
              });
              wfItem.strokeColor = "red";
              this.$refs.bflow.updateElemet(wfItem);
              return false;
            }
          } else if (wfItem.type == "userTask") {
            if (
              !wfItem.isInherit &&
              wfItem.formType == "1" &&
              wfItem.formCode &&
              !wfItem.formRelationId
            ) {
              this.$message({
                type: "warning",
                message: `${this.$t("请设置")}【${wfItem.name}】${this.$t("表单关联字段!")}`,
              });
              wfItem.strokeColor = "red";
              this.$refs.bflow.updateElemet(wfItem);
              return false;
            }
          }else if(wfItem.type == "subprocess"){
            if(!wfItem.wfschemeId || !wfItem.wfVersionId){
              this.$message({
                type: "warning",
                message: `${this.$t("请设置")}【${wfItem.name}】${this.$t("流程模版!")}`,
              });
              wfItem.strokeColor = "red";
              this.$refs.bflow.updateElemet(wfItem);
              return false;
            }
            
          }
        }
      } else {
        this.$message({
          type: "warning",
          message: this.$t("请完善【流程属性】信息!"),
        });
      }
      return res;
    },
    setForm(data) {
      let scheme = JSON.parse(data.scheme.f_Content);
      this.schemeinfoId = data.schemeinfo.f_Id;
      let baseinfo = {
        f_Id: data.schemeinfo.f_Id,
        f_Code: data.schemeinfo.f_Code,
        f_Name: data.schemeinfo.f_Name,
        f_Category: data.schemeinfo.f_Category,
        f_EnabledMark: data.schemeinfo.f_EnabledMark,
        f_Mark: data.schemeinfo.f_Mark,
        f_IsInApp: data.schemeinfo.f_IsInApp,
        f_Description: data.schemeinfo.f_Description,
        f_Icon: data.schemeinfo.f_Icon,
        f_Color: data.schemeinfo.f_Color,
        f_SchemeId: data.schemeinfo.f_SchemeId,
        f_SecretLevel: data.schemeinfo.f_SecretLevel,
        f_Company:data.schemeinfo.f_Company,
        f_SortCode:data.schemeinfo.f_SortCode,

        undoType: scheme.undoType,
        undoDbCode: scheme.undoDbCode,
        undoDbSQL: scheme.undoDbSQL,
        undoIOCName: scheme.undoIOCName,
        undoUrl: scheme.undoUrl,

        deleteType: scheme.deleteType,
        deleteDbCode: scheme.deleteDbCode,
        deleteDbSQL: scheme.deleteDbSQL,
        deleteIOCName: scheme.deleteIOCName,
        deleteUrl: scheme.deleteUrl,

        deleteDraftType: scheme.deleteDraftType,
        deleteDraftDbCode: scheme.deleteDraftDbCode,
        deleteDraftDbSQL: scheme.deleteDraftDbSQL,
        deleteDraftIOCName: scheme.deleteDraftIOCName,
        deleteDraftUrl: scheme.deleteDraftUrl,

        keywordDb: scheme.keywordDb,
        keywordTable: scheme.keywordTable,
        keywordRField: scheme.keywordRField,
        keywordSField: scheme.keywordSField,
      };

      let wfData = scheme.wfData;

      let auth = {
        f_AuthType: data.schemeinfo.f_AuthType,
        authData: data.schemeAuthList
          .filter((t) => t.f_Type != 2 && t.f_Type != 3)
          .map((t) => {
            return {
              id: t.f_ObjId,
              name: t.f_ObjName,
              type: t.f_ObjType,
            };
          }),
      };

      let authMonitor = {
        f_AuthType: data.schemeinfo.f_MonitorAuthType,
        authData: data.schemeAuthList
          .filter((t) => t.f_Type == 2)
          .map((t) => {
            return {
              id: t.f_ObjId,
              name: t.f_ObjName,
              type: t.f_ObjType,
            };
          }),
      };

      let authPrint = {
        authData: data.schemeAuthList
          .filter((t) => t.f_Type == 3)
          .map((t) => {
            return {
              id: t.f_ObjId,
              name: t.f_ObjName,
              type: t.f_ObjType,
            };
          }),
      };

      this.$refs.bflow.setData(wfData);
      this.$refs.shcemeinfo.setForm(baseinfo);
      this.$refs.auth.setForm(auth);
      this.$refs.authMonitor.setForm(authMonitor);
      this.$refs.authPrint.setForm(authPrint);
    },
    getForm() {
      // 1.获取流程配置基础属性
      let baseinfo = this.$refs.shcemeinfo.getForm();
      // 2.获取流程权限信息
      let auth = this.$refs.auth.getForm();
      let authMonitor = this.$refs.authMonitor.getForm();
      let authPrint = this.$refs.authPrint.getForm();
      // 3.流程节点信息
      const wfData = this.handleGetWFData();
      this.wfData = wfData;
      
      for(let node of wfData){
        if (node.type == "myline" && !node.isInit) {
          node.isInit = true;
          node.lineConditions = "";
          const fromNode = this.wfData.find((t) => t.id == node.from);
          if (fromNode.type == "userTask") {
            if (
              fromNode.btnlist.findIndex(
                (t) => t.code == "agree" && !t.hidden
              ) != -1
            ) {
              node.lineConditions = "agree"; // 流转条件
            }
          }
        }
      }

      let scheme = {
        wfData: wfData,

        keywordDb: baseinfo.keywordDb,
        keywordTable: baseinfo.keywordTable,
        keywordRField: baseinfo.keywordRField,
        keywordSField: baseinfo.keywordSField,

        undoType: baseinfo.undoType,
        undoDbCode: baseinfo.undoDbCode,
        undoDbSQL: baseinfo.undoDbSQL,
        undoIOCName: baseinfo.undoIOCName,
        undoUrl: baseinfo.undoUrl,

        deleteType: baseinfo.deleteType,
        deleteDbCode: baseinfo.deleteDbCode,
        deleteDbSQL: baseinfo.deleteDbSQL,
        deleteIOCName: baseinfo.deleteIOCName,
        deleteUrl: baseinfo.deleteUrl,

        deleteDraftType: baseinfo.deleteDraftType,
        deleteDraftDbCode: baseinfo.deleteDraftDbCode,
        deleteDraftDbSQL: baseinfo.deleteDraftDbSQL,
        deleteDraftIOCName: baseinfo.deleteDraftIOCName,
        deleteDraftUrl: baseinfo.deleteDraftUrl,
      };
      let dto = {
        schemeinfo: {
          f_Code: baseinfo.f_Code,
          f_Name: baseinfo.f_Name,
          f_Category: baseinfo.f_Category,
          f_EnabledMark: baseinfo.f_EnabledMark,
          f_Mark: baseinfo.f_Mark,
          f_IsInApp: baseinfo.f_IsInApp,
          f_AuthType: auth.f_AuthType,
          f_MonitorAuthType: authMonitor.f_AuthType,
          f_Description: baseinfo.f_Description,
          f_Icon: baseinfo.f_Icon,
          f_Color: baseinfo.f_Color,
          f_SchemeId: baseinfo.f_SchemeId,
          f_SecretLevel: baseinfo.f_SecretLevel,
          f_Company:baseinfo.f_Company,
          f_SortCode:baseinfo.f_SortCode
        },
        schemeAuthList:
          auth.f_AuthType == 1
            ? []
            : auth.authData.map((t) => {
                return {
                  f_ObjId: t.id,
                  f_ObjName: t.name,
                  f_ObjType: t.type,
                  f_Type:1,
                };
              }),
        scheme: {
          f_Content: this.lr_AESEncrypt(JSON.stringify(scheme), "learun"),
        },
      };

      if (authMonitor.f_AuthType != 1) {
        dto.schemeAuthList.push(
          ...authMonitor.authData.map((t) => {
            return {
              f_ObjId: t.id,
              f_ObjName: t.name,
              f_ObjType: t.type,
              f_Type:2,
            };
          })
        );
      }

      dto.schemeAuthList.push(
        ...authPrint.authData.map((t) => {
          return {
            f_ObjId: t.id,
            f_ObjName: t.name,
            f_ObjType: t.type,
            f_Type:3,
          };
        })
      );


      return dto;
    },
  },
};
</script>
